#coding:utf-8
import sys
import threading
import sqlite3
from ping3 import ping
import time

def ping_host(ip):
    """
    获取节点的延迟的作用
    :param node:
    :return:
    """
    ip_address = ip
    response = ping(ip_address,ttl=128)
    if response is not None:
        delay = float(response * 1000)
        return {'result':'OK','average':delay,'ip':ip,'lost':0}
    else :
        delay=100
        return {'result':'ERROR','average':delay,'ip':ip,'lost':100}

class MyThread(threading.Thread):
    def __init__(self, func, args, name=''):
        threading.Thread.__init__(self)
        self.name = name
        self.func = func
        self.args = args
        self.result = self.func(*self.args)

    def get_result(self):
        try:
            return self.result
        except Exception:
            return None


def main(ips):
    messages={}
    threads={}
    for ip in ips:
        # 循环 实例化2个Thread类，传递函数及其参数，并将线程对象放入一个列表中
        t = MyThread(ping_host, (ip,), 'thread_'+ip)
        threads[ip] = t
        t.start()  # 循环 开始线程

    for ip in threads.keys():
        threads[ip].join()  # 循环 join()方法可以让主线程等待所有的线程都执行完毕。
        messages[ip] = threads[ip].get_result()
        print(ip,messages[ip])
    return messages

if __name__ == '__main__':
    con=sqlite3.connect('./ping.db')
    cur = con.cursor()
    sql = "CREATE TABLE IF NOT EXISTS ping(host TEXT,ip TEXT,average FLOAT,lost FLOAT,time TIMESTAMP DEFAULT CURRENT_TIMESTAMP)"
    cur.execute(sql)
    sql= "INSERT INTO ping (host,ip,average,lost) values ('%s','%s',%f,%f)"
    try:
        while True:
            messages=main(sys.argv[1:])
            time.sleep(1)
            for ip in messages.keys():
                cur.execute(sql%(ip,messages[ip]['ip'],messages[ip]['average'],messages[ip]['lost']))
            con.commit()
    except KeyboardInterrupt:
        cur.close()
        con.close()
        print('terminated...')
        

        

